package com.mzy.tomcat.handler;

import com.mzy.tomcat.MzyTomcatV3;
import com.mzy.tomcat.http.MzyHttpRequest;
import com.mzy.tomcat.http.MzyHttpResponse;
import com.mzy.tomcat.servlet.MzyHttpServlet;
import com.mzy.tomcat.utils.FileUtils;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MzyRequestHandler implements Runnable {

    final private Socket socket;

    List<String> extensionNameList = new ArrayList<>();

    public MzyRequestHandler(Socket socket) {
        this.socket = socket;
        extensionNameList.add("html");
        extensionNameList.add("css");
        extensionNameList.add("js");
        extensionNameList.add("png");
        extensionNameList.add("jpg");
        extensionNameList.add("xml");
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 获取当前 socket 的输入和输出流
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            /*
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String requestHeader = "";
            while ((requestHeader = bufferedReader.readLine()) != null) {
                if (requestHeader.isEmpty()) break;
                System.out.println(requestHeader);
            }
            */

            /*outputStream = socket.getOutputStream();
            String responseHeader = "HTTP/2 200 OK\n" +
                    "content-type: text/html; charset=utf-8\n\n";
            String responseBody = responseHeader + "<h1>hello Tomcat  " + Thread.currentThread() + "</h1>";
            outputStream.write(responseBody.getBytes());*/

            // MzyCalServlet mzyCalServlet = new MzyCalServlet();

            // 构建 request 和 response 对象
            MzyHttpRequest request = new MzyHttpRequest(inputStream);
            MzyHttpResponse response = new MzyHttpResponse(outputStream);

            // 获取当前 uri
            String uri = request.getUri();
            // 判断是否是静态资源
            // 1. 获取uri的后缀
            String extensionName = FileUtils.getExtensionName(uri);
            // 2. 判断uri后缀是否是静态资源
            if (extensionNameList.contains(extensionName)) {
                // 读取
                InputStream is = ClassLoader.getSystemResourceAsStream(File.separator + uri);
                if (is != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                    String line;
                    StringBuilder responseBody = new StringBuilder();
                    while ((line = bufferedReader.readLine()) != null) {
                        responseBody.append(line);
                    }
                    // 响应给浏览器
                    response.write(responseBody.toString());
                    return;
                }
            }


            // 在 servletUrlMapping 中查找是否有匹配的 uri
            String servletName = MzyTomcatV3.servletUrlMapping.get(uri);
            // 如果 servletUrlMapping 容器中没有当前 uri 的映射
            if (servletName == null) {
                response.write("<h1>404 Not fond</h1>");
                return;
            }
            // 通过映射的 servletName 获取实际调用的 servlet
            MzyHttpServlet mzyHttpServlet = MzyTomcatV3.servletClassMapping.get(servletName);
            // 调用 service
            mzyHttpServlet.service(request, response);
            // mzyCalServlet.doGet(new MzyHttpRequest(inputStream), new MzyHttpResponse(outputStream));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }
}
